import { H3Event, eventHandler, readBody } from "h3";
import ObsClient from "esdk-obs-nodejs";


const obsClient = new ObsClient({
    // 推荐通过环境变量获取AKSK，这里也可以使用其他外部引入方式传入，如果使用硬编码可能会存在泄露风险
    // 您可以登录访问管理控制台获取访问密钥AK/SK，获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html
    access_key_id: process.env.OBS_ACCESS_KEY_ID,
    secret_access_key: process.env.OBS_SECRET_ACCESS_KEY,
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例，其他地区请按实际情况填写
    server: process.env.OBS_SERVER || "https://obs.ap-southeast-1.myhuaweicloud.com"
});

const bucketName = process.env.OBS_BUCKET;

// Helper to wrap OBS callbacks in Promises
const obsOperation = (operation, params) => {
    return new Promise((resolve, reject) => {
        obsClient[operation](params, (err, result) => {
            if (err) {
                reject(err);
            } else if (result.CommonMsg.Status >= 300) {
                reject(new Error(`OBS Error ${result.CommonMsg.Status}: ${result.CommonMsg.Code} - ${result.CommonMsg.Message}`));
            } else {
                resolve(result);
            }
        });
    });
};

export const uploadHandler = eventHandler(async (event) => {
    try {
        const body = await readBody(event);
        const { data } = body;

        if (!bucketName) {
            throw new Error("OBS_BUCKET environment variable is not set");
        }

        console.log("Uploading data to OBS bucket:", bucketName);

        await obsOperation('putObject', {
            Bucket: bucketName,
            Key: 'quiz_history.json',
            Body: JSON.stringify(data),
            ContentType: 'application/json'
        });

        return {
            success: true,
            message: "Upload successful",
        };
    } catch (error) {
        console.error("Upload error:", error);
        return {
            success: false,
            error: error.message || "Upload failed",
            status: 500,
        };
    }
});

export const downloadHandler = eventHandler(async (event) => {
    try {
        if (!bucketName) {
            throw new Error("OBS_BUCKET environment variable is not set");
        }

        console.log("Downloading data from OBS bucket:", bucketName);

        const result = await obsOperation('getObject', {
            Bucket: bucketName,
            Key: 'quiz_history.json',
        });

        // result.InterfaceResult.Content is the content
        const content = result.InterfaceResult.Content.toString();
        const data = JSON.parse(content);

        return {
            success: true,
            message: "Download successful",
            data: data,
        };
    } catch (error) {
        console.error("Download error:", error);
        return {
            success: false,
            error: error.message || "Download failed",
            status: 500,
        };
    }
});
